﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using System.Collections;
using HardwareLibrary.XMLLibrary;

namespace HardwareLibrary.FTPLibrary
{
    public class FtpHelper
    {
        public bool bThreadIsExit;
        FtpLib ftplib;
        public string ServerMainFolder;
        /// <summary>
        /// 上传成功与否标识
        /// </summary>
        public bool UpLoadedFlag;

        public void FtpFloderListenStart(FTP_Struct fi)
        {
            FtpFloderListenStart(fi.IpAddr, fi.User, fi.Pwd, fi.RemotePath, fi.Port);
        }

        public void FtpFloderListenStart(string ipAddress, string userName, string pwd, string serverFolder, int port)
        {
            ServerMainFolder = serverFolder;
            ftplib = new FtpLib(ipAddress, serverFolder, userName, pwd, port);
            ThreadStart ts1 = new ThreadStart(FTPfolderListening);
            Thread td = new Thread(ts1);
            td.Start();
        }
        /// <summary>
        /// 一个简单的文件夹监听方法，不过在ftp监听方面不适用，可参考。
        /// </summary>
        private void StartFileSystemWatching()
        {
            string listeningFolder = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\Tmp\";
            if (System.IO.Path.IsPathRooted(listeningFolder) == false)
            {
                return;
            }
            string BasePath = null;
            string Filter = null;
            if (System.IO.Directory.Exists(listeningFolder))
            {
                BasePath = listeningFolder;
                Filter = "*.xml";
            }
            else
            {
                BasePath = System.IO.Path.GetDirectoryName(listeningFolder);
                Filter = System.IO.Path.GetFileName(listeningFolder);
            }
            if (BasePath == null)
            {
                return;
            }
            BasePath = BasePath.Trim();
            if (BasePath.ToUpper().StartsWith(System.Windows.Forms.Application.StartupPath))
            {
                // 不能监视程序本身所在的目录的文件系统更改
                return;
            }
            if (System.IO.Directory.Exists(BasePath) == false)
            {
                // 不能监视不存在的目录
                return;
            }
            System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher();
            watcher.Path = BasePath;
            watcher.Filter = Filter;
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = false;
            watcher.Created += delegate(object sender, System.IO.FileSystemEventArgs args)
            {
                System.Windows.Forms.MessageBox.Show("发现XML文件");
            };
        }
        private void FTPfolderListening()
        {
            XMLOp xmlop = new XMLOp();
            bThreadIsExit = true;
            Hashtable ht;
            string TimeFolderString;
            string TimeFolders;
            bool IsXMLfileAllUpdated = true;
            string listeningFolder = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\Tmp\";
            if (Directory.Exists(listeningFolder) == false)
            {
                Directory.CreateDirectory(listeningFolder);
            }
            DirectoryInfo dir = new DirectoryInfo(listeningFolder);
            while (bThreadIsExit)
            {
                //文件检测,如果存在则打开ftp上传图片
                try
                {
                    foreach (FileInfo dChild in dir.GetFiles("*.xml"))
                    {
                        if (dChild != null)
                        {
                            ftplib.Connect();
                            //读取XML文件
                            ht = xmlop.ReadPicXML(dChild.FullName);
                            //上传XML内容中的文件
                            if (ht != null)
                            {
                                foreach (DictionaryEntry de in ht)
                                {
                                    if (File.Exists(de.Value.ToString()) == true)
                                    {
                                        TimeFolderString = xmlop.ReadPicXmlTime(dChild.FullName, de.Key.ToString());
                                        TimeFolders = DateTime.Parse(TimeFolderString).ToString("yyyy_MM/dd/");
                                        if (ftplib.ChDirFormRootFolder(ServerMainFolder + TimeFolders) == false)
                                        {
                                            ftplib.CreateDir(ServerMainFolder + TimeFolders);
                                        }
                                        if (ftplib.ChDirFormRootFolder(ServerMainFolder + TimeFolders) == true)
                                        {
                                            if (ftplib.Put(de.Value.ToString()) == false)
                                            {
                                                IsXMLfileAllUpdated = false;
                                            }
                                            else
                                            {
                                                File.Delete(de.Value.ToString());
                                            }
                                        }
                                        else
                                        {
                                            IsXMLfileAllUpdated = false;
                                        }
                                    }
                                }
                            }
                            //删除XML文件以及XML内容中标识的内容
                            if (IsXMLfileAllUpdated == true)
                            {
                                File.Delete(dChild.FullName);
                                ht.Clear();
                                UpLoadedFlag = true;
                            }
                        }
                    }
                }
                catch
                {
                    bThreadIsExit = false;
                }
                Thread.Sleep(1000);
            }
        }
    }
}
